package sein.android.hopenote;

import java.util.ArrayList;
import sein.android.hopenote.Const.HopeNoteDb;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.res.ColorStateList;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Item_Input extends Activity{
	
	private DBAdapter HnopenHelper;
	private SQLiteDatabase sdb;
	private	Button bt_i, bt_d, bt_a;
	private	EditText et_item, et_unit, et_group;
	private	Spinner spin_group, spin_item;
	private	Cursor cur_group, cur_item, list_cur;
	private	ArrayList<String> lst_group, lst_item, lst_unit;
	private ArrayList<Integer> lst_cnt;
	private	ArrayAdapter<String> adapter, adapter_item;
	private	ContentValues row;	// DB 삽입
	private TextView tv_group, tv_item;
	private String str_group, str_item, str_unit;	//항목 추가 혹은 삭제 할 때 사용.
	private int idx_group, idx_cnt;	//항목 추가 후 ChangeSpinGroup 함수에서 추가한 그룹을 spinner에 지정해주기 위한 index.
	private RadioGroup rdo_cnt;	//항목 입력 갯수(단일/복수)
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
        setContentView(R.layout.item_input);
        
        bt_i = (Button)findViewById(R.id.bt_insert);
        bt_d = (Button)findViewById(R.id.bt_delete);
        bt_a = (Button)findViewById(R.id.bt_normal_add);
        et_item = (EditText)findViewById(R.id.et_item);
        et_unit = (EditText)findViewById(R.id.et_unit);
        et_group = (EditText)findViewById(R.id.et_group);
        spin_group = (Spinner)findViewById(R.id.sp_group);
        spin_item = (Spinner)findViewById(R.id.sp_item);
        tv_group = (TextView)findViewById(R.id.tv_group);
        tv_item	= (TextView)findViewById(R.id.tv_item);
        rdo_cnt = (RadioGroup)findViewById(R.id.rdo_group);
        
        et_group.setVisibility(View.INVISIBLE);
        tv_group.setVisibility(View.INVISIBLE);
        et_item.setVisibility(View.INVISIBLE);
        tv_item.setVisibility(View.INVISIBLE);
        
        HnopenHelper = new DBAdapter(this);
        sdb = HnopenHelper.getReadableDatabase();
        
        //set group
        cur_group = sdb.query(true,HopeNoteDb.TB_ITEM, new String[] {HopeNoteDb.COL_GROUP}, null, null, null, null, null,null);
        cur_group.moveToFirst();
        lst_group = new ArrayList<String>();
        for(int i = 0; i < cur_group.getCount(); i++){
        	lst_group.add(cur_group.getString(0));
        	cur_group.moveToNext();
        }
        if(cur_group.getCount() < 9)
        {
        	lst_group.add("새 그룹 추가");
        }
        cur_group.close();
        spin_group.setPrompt("그룹 선택");
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lst_group);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin_group.setAdapter(adapter);
        
        //set item & unit
        String qWhere = HopeNoteDb.COL_GROUP + " = '" + spin_group.getSelectedItem().toString() + "'";
        cur_item = sdb.query(HopeNoteDb.TB_ITEM, new String[] {HopeNoteDb.COL_ITEM,HopeNoteDb.COL_UNIT,HopeNoteDb.COL_CNT}, qWhere, null, null, null, null);
        cur_item.moveToFirst();
        lst_item = new ArrayList<String>();
        lst_unit = new ArrayList<String>();
        lst_cnt = new ArrayList<Integer>();
        for(int i = 0; i < cur_item.getCount(); i++){
        	lst_item.add(cur_item.getString(0));
        	lst_unit.add(cur_item.getString(1));
        	lst_cnt.add(cur_item.getInt(2));
        	cur_item.moveToNext();
        }
        cur_item.close();
        lst_item.add("새 항목 추가");
        spin_item.setPrompt("항목 선택");
        adapter_item = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lst_item);
        adapter_item.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin_item.setAdapter(adapter_item);
    	
        //group Selection Event
    	spin_group.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				TextView tv = (TextView)arg1;
				if(tv.getText().toString().equals("새 그룹 추가"))
				{
					et_group.setVisibility(View.VISIBLE);
					tv_group.setVisibility(View.VISIBLE);
					et_item.setVisibility(View.VISIBLE);
					tv_item.setVisibility(View.VISIBLE);
				}
				else
				{
					et_group.setVisibility(View.INVISIBLE);
					tv_group.setVisibility(View.INVISIBLE);
				}
				ChangeSpinItem();
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
    	
    	//Item Selection Event
    	spin_item.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				TextView tv = (TextView)arg1;
				if(tv.getText().toString().equals("새 항목 추가"))
				{
					et_item.setVisibility(View.VISIBLE);
					tv_item.setVisibility(View.VISIBLE);
					bt_i.setClickable(true);
					//bt_i.setTextColor()
					bt_d.setClickable(false);
					et_unit.setText("");
					rdo_cnt.check(R.id.rdo_1);
					idx_cnt = 1;
				}
				else
				{
					et_item.setVisibility(View.INVISIBLE);
					tv_item.setVisibility(View.INVISIBLE);
					bt_i.setClickable(false);
					bt_d.setClickable(true);
					
					et_unit.setText(lst_unit.get(spin_item.getSelectedItemPosition()));
					switch(lst_cnt.get(spin_item.getSelectedItemPosition()))
					{
					case 1:
						rdo_cnt.check(R.id.rdo_1);
						break;
					case 2:
						rdo_cnt.check(R.id.rdo_2);
					}
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
    	
    	rdo_cnt.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				switch(checkedId)
				{
				case R.id.rdo_1:
					idx_cnt = 1;
					break;
				case R.id.rdo_2:
					idx_cnt = 2;
					break;
				}
			}
		});
    	
    	//항목 추가
    	bt_i.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				//check group selection
				if(spin_group.getSelectedItem().toString().equals("새 그룹 추가"))
				{
					if(et_group.getText().toString().replace(" ", "").equals(""))
					{
						Toast.makeText(Item_Input.this, "그룹을 입력해주세요.", Toast.LENGTH_SHORT).show();
						return;
					}
					else
					{
						str_group = et_group.getText().toString().replace(" ", "");
					}
				}
				else
				{
					str_group = spin_group.getSelectedItem().toString();
				}
				
				str_item = et_item.getText().toString().replace(" ", "");
				str_unit = et_unit.getText().toString().replace(" ", "");
				
				String qWhere = HopeNoteDb.COL_ITEM + " = '" + str_item + "'";
				list_cur = sdb.query(HopeNoteDb.TB_ITEM, new String[] {"1"}, qWhere, null, null, null, null);
				if(list_cur.getCount() == 0)
				{
					row = new ContentValues();
					row.put(HopeNoteDb.COL_GROUP, str_group);
					row.put(HopeNoteDb.COL_ITEM, str_item);
					row.put(HopeNoteDb.COL_UNIT, str_unit);
					row.put(HopeNoteDb.COL_CNT, idx_cnt);
					
					sdb.insert(HopeNoteDb.TB_ITEM, null, row);
					
					Toast.makeText(Item_Input.this, "추가 완료", Toast.LENGTH_SHORT).show();
					et_group.setText("");
					et_item.setText("");
					et_unit.setText("");
	
					ChangeSpinGroup();
					ChangeSpinItem();
				}
				else
				{
					Toast.makeText(Item_Input.this, "항목이 존재합니다.", Toast.LENGTH_SHORT).show();
				}
			}
		});
    	
    	//항목 삭제
    	bt_d.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// TODO Auto-generated method stub
				//check group selection
				str_group = spin_group.getSelectedItem().toString();
				str_item = spin_item.getSelectedItem().toString();
				
				String qWhere = HopeNoteDb.COL_ITEM + " = '" + str_item + "'";
				if(sdb.delete(HopeNoteDb.TB_ITEM, qWhere, null) > 0)
				{
					Toast.makeText(Item_Input.this, "삭제 완료", Toast.LENGTH_SHORT).show();
					ChangeSpinItem();
				}
				else
				{
					Toast.makeText(Item_Input.this, "삭제 실패", Toast.LENGTH_SHORT).show();
				}
			}
		});
    	
    	bt_a.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
			//View new Group Noamal_Add.java
				setContentView(R.layout.normal_add);
				
			}	
			
    	});
	}
	
	//reset spinner-group by addition or deletion
	private void ChangeSpinGroup() {
		//set group
        cur_group = sdb.query(HopeNoteDb.TB_ITEM, new String[] {HopeNoteDb.COL_GROUP}, null, null, HopeNoteDb.COL_GROUP, null, null);
        cur_group.moveToFirst();
        //lst_group = new ArrayList<String>();
        lst_group.clear();
        idx_group = 0;
        for(int i = 0; i < cur_group.getCount(); i++){
        	lst_group.add(cur_group.getString(0));
        	if(cur_group.getString(0) == str_group)
        	{
        		idx_group = i;
        	}
        	cur_group.moveToNext();
        }
        if(cur_group.getCount() < 9)
        {
        	lst_group.add("새 그룹 추가");
        }
        cur_group.close();
        adapter.notifyDataSetChanged();
        spin_group.setSelection(idx_group);	// call ChangeSpinItem by setOnItemSelectedListener
	}
	
	//reset spinner-item by spinner-group selection change.
	private void ChangeSpinItem() {
		//set item & unit
        String qWhere = HopeNoteDb.COL_GROUP + " = '" + spin_group.getSelectedItem().toString() + "'";
        cur_item = sdb.query(HopeNoteDb.TB_ITEM, new String[] {HopeNoteDb.COL_ITEM,HopeNoteDb.COL_UNIT,HopeNoteDb.COL_CNT}, qWhere, null, null, null, null);
        cur_item.moveToFirst();
        lst_item.clear();
        lst_unit.clear();
        lst_cnt.clear();
        for(int i = 0; i < cur_item.getCount(); i++){
        	lst_item.add(cur_item.getString(0));
            lst_unit.add(cur_item.getString(1));
            lst_cnt.add(cur_item.getInt(2));
        	cur_item.moveToNext();
        }
        lst_item.add("새 항목 추가");
        adapter_item.notifyDataSetChanged();
        spin_item.setSelection(cur_item.getCount());
        cur_item.close();
        
        /*if(spin_item.getSelectedItem().toString().equals("새 항목 추가"))
        {
        	unit.setText("");
        }
        else
        {
        	unit.setText(lst_unit.get(spin_item.getSelectedItemPosition()));
        }*/
	}
}
